package com.starlight.easybuyprictice.interceptor;

import com.starlight.easybuyprictice.entity.Token;
import com.starlight.easybuyprictice.service.TokenManager;
import com.starlight.easybuyprictice.util.WebUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Author yfy2001
 * @date 2022/11/28 20:39
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    private final TokenManager tokenManager;
    public TokenInterceptor(TokenManager tokenManager){
        this.tokenManager = tokenManager;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (method.getAnnotation(FreeTokenAuthentication.class) != null) {
            return true;
        }
        boolean tokenCorrected = false;
        Token token = null;
        try{
            String tokenValue = request.getHeader(Constants.TAG_TOKEN_VALUE);
            token = new Token(tokenValue);
            tokenCorrected=tokenManager.checkToken(token);
        }catch(NullPointerException | IllegalArgumentException e) {

        }
        if (tokenCorrected) {
            request.setAttribute(Constants.CURRENT_USER_ROLE,token.getType());
            return true ;
        }else {
            WebUtil.showInterceptionInfo(response,-1,"请先登录");
        }
        return false;
    }
}
